package com.sys.framework.web.service;

import com.sys.common.config.ThirdAuthConfigProperties;
import com.sys.common.constant.CacheConstants;
import com.sys.common.constant.Constants;
import com.sys.common.constant.UserConstants;
import com.sys.common.core.domain.entity.SysUser;
import com.sys.common.core.domain.model.LoginUser;
import com.sys.common.core.redis.RedisCache;
import com.sys.common.exception.ServiceException;
import com.sys.common.exception.user.*;
import com.sys.common.utils.AuthUtils;
import com.sys.common.utils.DateUtils;
import com.sys.common.utils.MessageUtils;
import com.sys.common.utils.StringUtils;
import com.sys.common.utils.ip.IpUtils;
import com.sys.framework.manager.AsyncManager;
import com.sys.framework.manager.factory.AsyncFactory;
import com.sys.framework.security.context.AuthenticationContextHolder;
import com.sys.system.domain.fo.BindThirdAuthFO;
import com.sys.system.service.ISysConfigService;
import com.sys.system.service.ISysUserService;
import com.sys.system.service.ISysUserThirdAuthService;
import me.zhyd.oauth.cache.AuthDefaultStateCache;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 登录校验方法
 *
 * @author LGY
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;
    @Resource
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysUserThirdAuthService sysUserThirdAuthService;
    @Autowired
    private ThirdAuthConfigProperties thirdAuthConfigProperties;
    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(String userId) {
        SysUser sysUser = new SysUser();
        sysUser.setId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 第三方授权登录
     *
     * @param type 类型
     * @return
     */
    public String getThirdLoginAuthUrl(String type) {
        List<ThirdAuthConfigProperties.App> apps = thirdAuthConfigProperties.getApps();
        if (CollectionUtils.isEmpty(apps)) {
            throw new ServiceException("未配置第三方授权登录");
        }
        Map<String, ThirdAuthConfigProperties.App> authMap = apps.stream().collect(Collectors.toMap(ThirdAuthConfigProperties.App::getType, Function.identity()));
        ThirdAuthConfigProperties.App authApp = authMap.get(type);
        if (authApp == null) {
            throw new ServiceException("未配置该平台的授权");
        }
        AuthRequest authRequest = AuthUtils.getAuthRequest(authApp, AuthDefaultStateCache.INSTANCE);
        return authRequest.authorize(AuthStateUtils.createState());
    }

    public String thirdLogin(BindThirdAuthFO thirdAuthFO) {
        Map<String, ThirdAuthConfigProperties.App> supportAppMap =
                thirdAuthConfigProperties.getApps().stream().collect(Collectors.toMap(ThirdAuthConfigProperties.App::getType, app -> app));
        ThirdAuthConfigProperties.App bindApp = supportAppMap.get(thirdAuthFO.getType());
        if (bindApp == null) {
            throw new ServiceException("未配置该平台的授权");
        }
        AuthRequest authRequest = AuthUtils.getAuthRequest(bindApp, AuthDefaultStateCache.INSTANCE);
        AuthCallback authCallback = AuthCallback.builder()
                .state(thirdAuthFO.getState())
                .code(thirdAuthFO.getCode())
                .build();
        AuthResponse<AuthUser> resp = authRequest.login(authCallback);
        if (!resp.ok()) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(thirdAuthFO.getType() + "授权登录", Constants.LOGIN_FAIL, "第三方授权登录异常"));
            throw new ServiceException("第三方授权登录异常，请联系管理员");
        }
        String thirdAuthUUId = resp.getData().getUuid();
        SysUser user = sysUserThirdAuthService.getUserByThirdTypeAndUUid(thirdAuthUUId, thirdAuthFO.getType());
        if (user == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(thirdAuthFO.getType() + "_" + thirdAuthUUId, Constants.LOGIN_FAIL, "未绑定该平台的三方登录"));
            throw new ServiceException("未绑定该平台的三方登录，请先登录或注册绑定");
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, thirdAuthFO.getType() + "授权登录成功"));
        LoginUser loginUser = new LoginUser(user.getId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
        return tokenService.createToken(loginUser);
    }
}
